package local.blueheart.data.springdatademo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(URLUtil.class);

    public static String getProtocol(String url){
        URL Url = genernateURL(url);
        if(Url!=null){
            return Url.getProtocol();
        }else {
            return "";
        }
    }

    public static String getAuthority(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getAuthority():"";
    }

    public static String getHost(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getHost():"";
    }

    public static int getPort(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getPort():80;
    }

    public static String getPath(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getPath():"";
    }

    public static String getLastPath(String aUrl) throws UnsupportedEncodingException {
        String path = getPath(aUrl);
        if(StringUtil.isNotBlank(path)){
            String[] paths = path.split("/");
            return URLDecoder.decode(paths[paths.length-1],"UTF-8");
        }else{
            return "";
        }
    }

    public static String getFileName(String fileFullName){
        if(fileFullName.contains(".")){
            return fileFullName.split("\\.")[0];
        }
        return fileFullName;
    }

    public static String getExtName(String fileFullName){
        if(fileFullName.contains(".")){
            return fileFullName.split("\\.")[1];
        }
        return "";
    }


    public static String getQuery(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getQuery():"";
    }

    public static String getFile(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getFile():"";
    }

    public static String getRef(String aUrl){
        URL url = genernateURL(aUrl);
        return url!=null?url.getRef():"";
    }


    private static URL genernateURL(String url){
        URL aURL = null;
        try {
            aURL = new URL(url);
        } catch (MalformedURLException e) {
            LOGGER.error("url转换出错",e);
        }finally {
            return aURL;
        }
    }

    public static void main(String[] args){
        String urlStr = "http://devemis.jx.chinamobile.com/lib/fsarchive/fsarchivestore_B5T9QH.nsf/0/C7CF6C8D7FBCCB1C4825835400303DB8?openDocument";
        String a = URLUtil.getPath(urlStr);
        System.out.println(a);
    }

    public static String encode(String fileFullName) {
        String encode = URLEncoder.encode(fileFullName);
        return encode;
    }
}
